package cmd

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"

	"github.com/ouqiang/delay-queue/config"
	"github.com/ouqiang/delay-queue/delayqueue"
	"github.com/ouqiang/delay-queue/routers"
)

// Cmd 应用入口Command
type Cmd struct{}

var (
	G_version    bool
	G_configFile string
)

const (
	// AppVersion 应用版本号
	AppVersion = "0.4"
)

// Run 运行应用
func (cmd *Cmd) Run() {

	// 解析命令行参数
	cmd.parseCommandArgs()
	//如果有打印版本的命令,就只打印版本,然后退出
	if G_version {
		fmt.Println(AppVersion)
		os.Exit(0)
	}
	// 初始化配置
	config.Init(G_configFile)
	// 初始化队列
	delayqueue.Init()

	// 运行web server
	cmd.runWeb()
}

// 解析命令行参数
func (cmd *Cmd) parseCommandArgs() {
	//fmt.Printf("%+v\n", os.Args)

	// 指定配置文件,默认用同目录内的conf文件
	flag.StringVar(&G_configFile, "c", "delay-queue.conf", "./delay-queue -c ./delay-queue.conf")
	// 默认不输出版本
	flag.BoolVar(&G_version, "v", false, "./delay-queue -v")
	flag.Parse()
	//要查看解析结果,必须在Parse函数后调用回显
	//fmt.Printf("配置文件:%+v\n", G_configFile)
	//fmt.Printf("版本:%+v\n", G_version)

}

// 运行Web Server
func (cmd *Cmd) runWeb() {
	http.HandleFunc("/push", routers.Push)
	http.HandleFunc("/pop", routers.Pop)
	http.HandleFunc("/finish", routers.Delete)
	http.HandleFunc("/delete", routers.Delete)
	http.HandleFunc("/get", routers.Get)

	log.Printf("listen %s\n", config.Setting.BindAddress)
	err := http.ListenAndServe(config.Setting.BindAddress, nil)
	log.Fatalln(err)
}
